package com.pmt.feedplayer.android

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.core.content.ContextCompat
import com.pmt.feedplayer.data.LocalVideoScanner
import com.pmt.feedplayer.ui.VideoFeed
import com.pmt.feedplayer.ui.VideoListViewModel
import com.pmt.feedplayer.ui.VideoPlayerScreen
import android.speech.SpeechRecognizer as AndroidSpeechRecognizer

class MainActivity : ComponentActivity() {
    
    // 权限相关 - 根据Android版本使用不同的权限
    private val requiredPermissions: Array<String> get() {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13及以上使用细粒度媒体权限
            arrayOf(
                Manifest.permission.READ_MEDIA_VIDEO, // 视频访问权限
                Manifest.permission.RECORD_AUDIO  // 添加录音权限用于语音识别
            )
        } else {
            // Android 12及以下使用旧权限模型
            arrayOf(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.RECORD_AUDIO
            )
        }
    }
    
    // 多权限请求器
    private val multiplePermissionsLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        val allGranted = permissions.all { it.value }
        if (allGranted) {
            // 所有权限已授予，加载视频
            loadVideos()
        } else {
            // 显示权限被拒绝的提示
            showPermissionDeniedMessage()
        }
    }
    
    private lateinit var viewModel: VideoListViewModel
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 检查语音识别是否可用
        if (!AndroidSpeechRecognizer.isRecognitionAvailable(this)) {
            // 语音识别不可用，显示提示
            showSpeechRecognitionUnavailableMessage()
        }
        
        // 创建LocalVideoScanner并设置上下文
        val videoScanner = com.pmt.feedplayer.data.LocalVideoScanner()
        videoScanner.setContext(this)
        
        // 创建ViewModel
        viewModel = VideoListViewModel(videoScanner)
        
        setContent {
            MyApplicationTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    AppNavigation(viewModel = viewModel)
                }
            }
        }
        
        // 检查并请求权限
        checkAndRequestPermissions()
    }
    
    private fun checkAndRequestPermissions() {
        // 检查是否所有权限都已授予
        val allPermissionsGranted = requiredPermissions.all {
            ContextCompat.checkSelfPermission(this, it) == PackageManager.PERMISSION_GRANTED
        }
        
        if (allPermissionsGranted) {
            // 所有权限已授予
            loadVideos()
        } else {
            // 请求缺失的权限
            multiplePermissionsLauncher.launch(requiredPermissions)
        }
    }
    
    private fun showPermissionDeniedMessage() {
        // 显示权限被拒绝的提示
        val message = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            "需要视频和录音权限才能使用完整功能"
        } else {
            "需要存储和录音权限才能使用完整功能"
        }
        android.widget.Toast.makeText(
            this,
            message,
            android.widget.Toast.LENGTH_LONG
        ).show()
    }
    
    private fun showSpeechRecognitionUnavailableMessage() {
        // 显示语音识别不可用的提示
        android.widget.Toast.makeText(
            this,
            "当前设备不支持语音识别功能",
            android.widget.Toast.LENGTH_LONG
        ).show()
    }
    
    private fun loadVideos() {
        // 加载最多10个本地视频
        viewModel.loadLocalVideos(10)
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LocalVideoListScreen(viewModel: VideoListViewModel) {
    Scaffold(
        // 当showPlayer为false时显示topBar，为true时隐藏topBar
        topBar = {
            if (!viewModel.showPlayer.value) {
                TopAppBar(title = { Text("本地视频") })
            }
        }
    ) {
        Box(modifier = Modifier.fillMaxSize().padding(if (!viewModel.showPlayer.value) it else androidx.compose.foundation.layout.PaddingValues())) {
            // 显示视频列表
            com.pmt.feedplayer.ui.VideoFeed(
                videos = viewModel.videoListState.value,
                onVideoClick = { video: com.pmt.feedplayer.data.VideoItem -> viewModel.onVideoClick(video) },
                onLoadMore = { viewModel.loadMoreVideos(10) }
            )
            
            // 当showPlayer为true时，显示视频播放页面
            if (viewModel.showPlayer.value && viewModel.selectedVideo.value != null) {
                viewModel.selectedVideo.value?.let { video ->
                    com.pmt.feedplayer.ui.VideoPlayerScreen(
                        videoItem = video,
                        onBack = { viewModel.closePlayer() }
                    )
                }
            }
        }
    }
}

@Preview
@Composable
fun DefaultPreview() {
    MyApplicationTheme {
        Surface(modifier = Modifier.fillMaxSize()) {
            Text("预览模式")
        }
    }
}
